#!/usr/bin/env python3
# coding=utf-8
##########################################################################
# Author: wangdj
# mail: wangdajunttf@163.com
# Created Time: Thu 28 Oct 2021 04:27:56 PM CST
##########################################################################

from time import gmtime
from time import strftime
import copy
import json
import os
import sys
import time
import re
from subprocess import Popen, PIPE, STDOUT, run
from rich import print, print_json
from rich.console import Console
console = Console()


# 执行 ffmpeg 命令会卡住不实时输出
def exe_command(command):
  """
  执行 shell 命令并实时打印输出
  :param command: shell 命令
  :return: process, exitcode
  """
  print(command)
  process = Popen(command,
                  stdout=PIPE,
                  stderr=STDOUT,
                  shell=True,
                  encoding="utf-8")
  with process.stdout:
    for line in process.stdout.readlines():
      print(line)
  exitcode = process.wait()
  return process, exitcode


# 执行 ffmpeg 命令不会卡住，实时输出
def run_shell(shell):
  print(':vampire:[bold magenta]$[/bold magenta]', shell)
  cmd = Popen(shell,
              stdin=PIPE,
              stderr=sys.stderr,
              close_fds=True,
              stdout=sys.stdout,
              universal_newlines=True,
              shell=True,
              bufsize=1)
  cmd.communicate()
  return cmd.returncode


# if __name__ == '__main__':
#  print(run_shell("ping www.baidu.com"))
# sys.exit()


# 执行 要等待的 命令会卡住不实时输出，可以拿到输出结果
def cmd(command):
  subp = Popen(command,
               shell=True,
               stdout=PIPE,
               stderr=PIPE,
               encoding="utf-8")
  subp.wait(5)
  if subp.poll() == 0:
    return subp.stdout.readlines()
  else:
    print('失败')


interval = 10
thisPath = os.path.split(os.path.realpath(__file__))[0]
# jsonDataF = '/home/ttf08153/videoff'

videoFs = [
    '$HOME/ggmount/tmp/testTree/Three.Kingdoms.2010.S01E92.1080p60.BluRay.x264.AAC.mp4']
# with open(jsonDataF, 'r', encoding='utf8') as f:
#   videoFs = f.readlines()
# print(videoFs)
# sys.exit()

imgGdP = f'$HOME/ggmount/ttfa/video_image'

for fp in videoFs:
  fp = fp.strip()
  shellReturnCode = run_shell(
      f'[ -f "{fp}" ]'
  )
  if shellReturnCode != 0:
    print(f'{fp} 文件不存在！')
    continue

  fn = re.findall(r'[^/]+$', fp)[0]  # 文件名
  imgGdPFull = f'{imgGdP}/{fn}'
  run_shell(f'mkdir -pv "{imgGdPFull}"')

  duration = cmd(
      f'ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "{fp}"')[0].strip()
  print(f"=> 视频时长:",
        strftime("%H:%M:%S", gmtime(int(float(duration)))),
        duration
        )
  startSec = 0
  while startSec < float(duration):
    # 图片文件名，把秒数格式化
    imgName = strftime("%H:%M:%S", gmtime(startSec))
    os.system(
        f'ffmpeg -ss {startSec} -i "{fp}" -n -vframes 1 -r 1 -lossless 0 "{imgGdPFull}/{imgName}.jpg" 2>&1 | egrep "(^Output|already exists. Exiting)"')
    startSec = startSec + interval
